package com.taiyo.modules.api.controller;

import com.taiyo.common.utils.R;
import com.taiyo.modules.api.annotation.AuthIgnore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.file.Paths;
import java.util.Map;

/**
 * Created by admin on 2018/1/30.
 */
@RestController
@RequestMapping("/api/img")
public class UpPicController {

    @Autowired
    private  ResourceLoader resourceLoader;

    public static final String ROOT = "C:/dayoImg/";

    @GetMapping("/{filename:.+}")
    @AuthIgnore
    public ResponseEntity<?> getFile(@PathVariable String filename) {

        try {
            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(ROOT, filename).toString()));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

    @PostMapping("/upimg")
    public R handleFileUpload(@RequestParam Map<String, Object> params) {
        return R.ok(generateImage((String) params.get("img")));
    }

    //base64字符串转化成图片
    public static String generateImage(String imgStr)
    {   //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) //图像数据为空
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        try
        {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {
                    b[i]+=256;
                }
            }
            String imgName=System.currentTimeMillis()+".jpg";
            String imgFilePath = ROOT+imgName;//新生成的图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return imgName;
        }
        catch (Exception e)
        {
            return null;
        }
    }

}
